package com.irain.pp.tool.mybatis.pagehelper;

import com.github.pagehelper.Page;
import com.github.pagehelper.dialect.helper.MySqlDialect;
import org.apache.ibatis.cache.CacheKey;

/**
 * @author WangYanPeng
 * @date 2017/10/19 17:19
 */
public class PpMySqlDialect extends MySqlDialect {


    /**
     * 重写带有for update 的分页拼接逻辑
     * @param sql
     * @param page
     * @param pageKey
     * @return
     */
    @Override
    public String getPageSql(String sql, Page page, CacheKey pageKey) {
        int index = sql.lastIndexOf("FOR UPDATE",sql.length() - 10);
        StringBuilder sqlBuilder = new StringBuilder(sql.length() + 14);
        sqlBuilder.append(sql);
        if (index != -1){
            sqlBuilder.delete(index,sql.length());
        }
        if (page.getStartRow() == 0) {
            sqlBuilder.append(" LIMIT ? ");
        } else {
            sqlBuilder.append(" LIMIT ?, ? ");
        }
        if (index != -1){
            sqlBuilder.append("FOR UPDATE");
        }
        pageKey.update(page.getPageSize());
        return sqlBuilder.toString();
    }
}
